﻿function MainController($scope, $state, $stateParams, $searchType) {
    MainController.prototype.$inject = ['$scope', '$state', '$stateParams', '$searchType'];
    $scope.isAuthentificate = isAuth;
    $scope.$searchType = $searchType
    $scope.$state = $state;
    $scope.$stateParams = $stateParams;
    if ($stateParams.type !== undefined && $stateParams.type !== null) {
        angular.forEach($scope.$searchType.searchTypes, function (v) {
            if (v.type === $stateParams.type) {
                $scope.$searchType.selected = v;
            }
        });
    }
}
function registrationController($scope) {
    registrationController.prototype.$inject = ['$scope'];
    $scope.IsServerError = false;
    $scope.ErrorMessage = [];
    $scope.OkMessage = '';
    $scope.user = { username: '', password: '', confirmpassword: '' };
    $scope.IsRequest = false;
    $scope.submit = function () {
        //if (!form.$valid) return;
        var token = $(document.querySelectorAll('[name=__RequestVerificationToken]')).val();
        console.log("submit 1 IsRequest" + $scope.IsRequest);
        if (!$scope.IsRequest) {
            $scope.IsRequest = true;
            console.log("submit 2 IsRequest" + $scope.IsRequest);
            $.ajax('/Account/JsonRegister',
                {
                    type: "POST",
                    data:
                    {
                        __RequestVerificationToken: token,
                        UserName: $scope.user.username,
                        Password: $scope.user.password,
                        ConfirmPassword: $scope.user.password
                    },
                    success: function (data) {
                        $scope.IsRequest = false;
                        if (data.success != null && data.success == true) {
                            $scope.IsServerError = false;
                            location.reload()
                        } else if (data.errors != null && data.errors.length > 0) {
                            $scope.IsServerError = true;
                            $scope.ErrorMessage = data.errors
                        } else {
                            $scope.IsServerError = true;
                            $scope.ErrorMessage.push('У нас произошла ошибка, уже работаем над этим.');
                        }
                        $scope.$apply();
                    },
                    error: function (data) {
                        $scope.IsRequest = false;
                        $scope.IsServerError = true;
                        if (data.errors != null && data.errors.length > 0) {
                            $scope.ErrorMessage = data.errors;
                        }
                        $scope.$apply();
                    }
                })
        }
    }
}
function loginUserContrller($scope) {
    console.log('loginUserControllerCreated');
    loginUserContrller.prototype.$inject = ['$scope'];
    $scope.IsServerError = false;
    $scope.ErrorMessage = 'У нас произошла ошибка, уже работаем над этим.';
    $scope.OkMessage = '';
    $scope.IsRequest = false;
    $scope.user = { username: '', password: '', rememberMe: false };
    $scope.submit = function () {
        var token = $(document.querySelectorAll('[name=__RequestVerificationToken]')).val();
        if ($scope.IsRequest) return;
        $scope.IsRequest = true;
        console.log("request");
        $.ajax('/Account/JsonLogin',
            {
                type: "POST",
                data:
                    {
                        __RequestVerificationToken: token
                        , UserName: $scope.user.username
                        , Password: $scope.user.password
                        , RememberMe: $scope.user.rememberMe
                    },
                success: function (data) {
                    $scope.IsRequest = false;
                    if (data.success != null && data.success == true) {
                        $scope.IsServerError = false;
                        location.reload()
                    } else if (data.errors != null && data.errors.length > 0) {
                        $scope.IsServerError = true;
                        $scope.ErrorMessage = data.errors.join("\n");
                    } else {
                        $scope.IsServerError = true;
                        $scope.ErrorMessage = "Очень странная ошибка, такой вообще по идее быть не должно.";
                    }
                    $scope.$apply();
                },
                erorr: function (data) {
                    $scope.IsRequest = false;
                    $scope.IsServerError = true;
                    if (data.errors != null && data.errors.length > 0) {
                        $scope.ErrorMessage = data.errors;
                    }
                    $scope.$apply();
                }
            });
    };
};
function addSiteController($scope, $http) {
    //console.log("addSiteController1");
    addSiteController.prototype.$inject = ['$scope', '$http'];
    $scope.IsServerError = false;
    $scope.ErrorMessage = []; //'У нас произошла ошибка, уже работаем над этим.';
    $scope.OkMessage = "";
    $scope.titleIsChanged = false;
    $scope.IsRequest = false;
    //console.log("addSiteController2");
    //$scope.tagSeparatorRegExp = tagseparator;
    //console.log(tagSeparatorRegExp);
    $scope.bookmark = {};
    $scope.bookmark.url = "";
    $scope.bookmark.userTags = [];
    //$scope.bookmark.userTags.push("init");
    $scope.bookmark.userTitle = "";
    $scope.submit = function () {
        if ($scope.IsRequest) return;
        $scope.IsRequest = true;
        console.log('submited'); console.log($scope.bookmark);
        $http.post('api/Bookmark/Create ',
            {
                url: $scope.bookmark.url,
                tags: $scope.bookmark.userTags,
                title: $scope.bookmark.userTitle
            })
        .success(function (data) {
            $scope.IsRequest = false;
            if (data.item["status@"] == "ok") {
                $scope.OkMessage = "Теги добавлены!";
            }
            else {
                $scope.IsServerError = true;
                $scope.ErrorMessage = data.item["data@"]
            }
            console.log("success");
        })
        .error(function (data, s) {
            $scope.IsRequest = false;
            console.log("error");
            console.log(data);
            if (s != 404) {
                //angular.forEach(data.ExceptionMessage, $scope.ErrorMessage.push)
                $scope.ErrorMessage.push(ExceptionMessage)
            }
            //console.log(data);
            // $scope.$apply();
        });
    }
    $scope.blur = function () {
        $http.get('/api/url/GetTitle', { params: { url: $scope.bookmark.url } })
        .success(function (data) {
            if (!$scope.titleIsChanged) {
                $scope.bookmark.userTitle = angular.fromJson(data);
            }
            $scope.titleIsChanged = false;
        })
        .error(function (data) {
            $scope.titleIsChanged = false;
            $scope.ErrorMessage.push(data);
        });
    }
    //$scope.GetNewMessge = function () { $scope.OkMessage = $scope.bookmark.userTags.length > 1 ? 'Круто! Теги: ' + $scope.bookmark.userTags.join(", ") : 'Тег: ' + $scope.bookmark.userTags[0]; }
    //addSiteForm.tagList.val = 'a'
    //console.log(addSiteForm.tagList);
    //$scope.bookmark.userTags.pop();
}
function reportController($scope) {
    reportController.prototype.$inject = ['$scope'];
    $scope.IsServerError = false;
    $scope.ErrorMessage = 'Извините. На данный момент не реализована отправка отчетов.';
    $scope.OkMessage = '';
    $scope.IsOk = false;
    $scope.report = { subject: '', message: '', contact: '' };
    $scope.IsRequest = false;
    $scope.submit = function () { $scope.IsServerError = true; }
};
function IndexController($scope, $location, $http) {
    console.log("IndexController");
    //console.log(this.constructor);
    IndexController.prototype.$inject = ['$scope', '$location', '$http'];
    $scope.CreateTag = function (str) {
        $('#tags').tagit('createTag', str);
    }

    function init() {
        $scope.inputedTagText = "";
        $scope.tagsForSearch = [];
        $scope.IsSearching = $scope.$state.is('search');
        if ($scope.IsSearching) {
            $scope.CurrentPage = 0;
            $scope.IsLoading = false;
            $scope.searchResultsEven = [];
            $scope.searchResultsOdd = [];
            var tags = $scope.$stateParams.tags;
            var tagsString = "";
            try {
                tagsString = tags.join(" ");
                angular.forEach(tags, $scope.CreateTag);
            }
            catch (Ex) {
                tagsString = tags.split(tagseparator).join(" ");
                angular.forEach(tags.split(tagseparator), $scope.CreateTag);
            }
            $scope.loadMore = function () {
                if ($scope.IsLoading) return;
                $scope.IsLoading = true;
                var queryStringHttp = $scope.$searchType.selected.type == 'general' ? '/api/Search/ByTags/' + tagsString : '/api/Search/ByUserTags/' + tagsString;
                $http.get(queryStringHttp, { params: { skip: $scope.CurrentPage * 10 } })
                    .success(function (data, status) {
                        console.log(data)
                        angular.forEach(data, function (v, i) {
                            console.log(v);
                            //var ob = $.parseJSON(v)// angular.fromJson(v)
                            //console.log(ob)
                            if (i % 2 == 0) { $scope.searchResultsEven.push(v); }
                            else { $scope.searchResultsOdd.push(v) };
                        });
                        $scope.IsLoading = false;
                    })
                    .error(function (data, status) {
                        console.log(data); console.log(status);
                        $scope.IsLoading = false;
                    })
                $scope.CurrentPage = $scope.CurrentPage + 1;
            }

            $scope.loadMore();
        }
    }
    initTagIt();
    init();


    $scope.inputTagChanged = function () {
        var rawTags = $scope.inputedTagText;
        if ($.inArray(rawTags, tagseparatorsArray) != -1) {
            $scope.inputedTagText = "";
        }
        if (rawTags.length > 1) {
            var tagsToWrap = rawTags.split(tagseparator);
            console.log(tagsToWrap);
            if (tagsToWrap.length > 1) {
                angular.forEach(tagsToWrap, function (v) {
                    $scope.CreateTag(v);
                });
                self.InputTagText = "";
            };
        };
    };
    $scope.submit = function () {
        $(document.querySelector('[name=tags]')).remove();
        var tagsForSearchArray = [];
        var tagsNodeList = document.querySelectorAll('#tags .tagit-choice > span');
        //var temQueryStr = "";
        if (tagsNodeList.length == 0) return;
        for (var i = 0; i < tagsNodeList.length; i++) {
            tagsForSearchArray.push(tagsNodeList[i].innerText);
            //temQueryStr += tagsNodeList[i].innerText;
            //if (i + 1 != tagsNodeList.length) temQueryStr += " ";
        }
        //console.log(tagsForSearchArray);
        $scope.$state.go('search', { tags: tagsForSearchArray, type: $scope.$searchType.selected.type });
        //$location.path("/search").search()
        //$(document.querySelector('#tagSearch')).submit();
    }

    $scope.changeSearchType = function (searchType) {
        $scope.$searchType.selected = searchType;
        $scope.submit();
    }
};
function ManageController($scope, $http) {
    ManageController.prototype.$inject = ['$scope', '$http'];
    console.log("ManageController");
    console.log($scope)
    console.log(this);
};
function TagsController() {
    console.log("TagsController")
};